<template>
  <el-dialog
    class="progress-download-excel-model"
    title="设置计划值"
    :close-on-click-modal="false"
    :destroy-on-close="true"
    :visible="visible"
    :width="$setRem(500)"
    :before-close="handleCancel">
    <div class="btns">
      <i class="iconfont iconchakanlishicaozuo" title="查看历史记录" @click="historyVisible = true"></i>
      <i class="iconfont iconxinjian" title="新建计划" @click="handleAdd"></i>
    </div>
    <el-table
      class="table-content"
      v-loading="tableLoading"
      element-loading-custom-class="custom-load"
      :max-height="$setRem(500)"
      :data="tableData">
      <el-table-column prop="date" label="日期"></el-table-column>
      <el-table-column prop="plan_number" label="计划人数"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <span class="btn" @click="handleEdit(scope.row)">编辑</span>
          <span class="btn" @click="handleDelete(scope.row)">删除</span>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-if="total > 10"
      :page-size="pageSize"
      :current-page="pageNo"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <el-dialog
      :title="planTitle"
      class="add-plan-model"
      destroy-on-close
      append-to-body
      :width="$setRem(450)"
      :visible="addVisible">
      <el-form :model="form" ref="form" :label-width="$setRem(100)">
        <el-form-item
          label="日期"
          prop="date"
          :rules="[
              { required: true,  message: '日期不能为空', trigger: 'change' }
            ]"
        >
          <el-date-picker
            v-model="form.date"
            type="month"
            placeholder="选择日期时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="计划人数"
          prop="plan_number"
          :rules="[
              { required: true,  message: '计划人数不能为空', trigger: 'blur' }
            ]"
        >
          <el-input
            placeholder="请输入"
            v-model="form.plan_number"
            @keydown.native.enter="handleSubmit"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addVisible = false">取 消</el-button>
        <el-button
          class="success"
          type="primary"
          :loading="btnLoading"
          @click="handleSubmit">
          确 定
        </el-button>
      </div>
    </el-dialog>
    <el-dialog
      :width="$setRem(500)"
      :max-height="$setRem(500)"
      title="历史记录"
      :visible.sync="historyVisible"
      append-to-body>
      <el-table
        class="table-content"
        v-loading="historyTableLoading"
        element-loading-custom-class="custom-load"
        :data="historyTableData">
        <el-table-column prop="date" label="日期"></el-table-column>
        <el-table-column prop="plan_number" label="计划人数"></el-table-column>
        <el-table-column prop="uploadDate" label="上传时间"></el-table-column>
      </el-table>
      <el-pagination
        v-if="historyTotal > 10"
        :page-size="historyPageSize"
        :current-page="historyPageNo"
        layout="total, sizes, prev, pager, next, jumper"
        :total="historyTotal"
        @size-change="handleHistorySizeChange"
        @current-change="handleHistoryCurrentChange"
      />
    </el-dialog>
  </el-dialog>
</template>

<script>
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    date: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      pageNo: 1,
      pageSize: 10,
      total: 0,
      tableLoading: false,
      tableData: [],
      // 新增弹框
      addVisible: false,
      // 新增保存loading
      btnLoading: false,
      type: 'add',
      // 查看历史弹框
      historyVisible: false,
      historyTableLoading: false,
      historyTableData: [],
      historyTotal: 0,
      historyPageSize: 1,
      historyPageNo: 10,
      form: {
        plan_number: '',
        date: ''
      }
    };
  },
  computed: {
    // 项目id
    projectId() {
      return this.$store.state.currentProjectId;
    },
    planTitle() {
      return `${this.type === 'add' ? '新增' : '编辑'}计划`;
    }
  },
  watch: {
    visible(val) {
      if (val) {
        this.getPlanData();
      }
    },
    historyVisible(val) {
      val && this.getHistory();
    },
    addVisible(val) {
      if (!val) {
        this.form = {
          plan_number: '',
          date: ''
        };
      }
    }
  },
  methods: {
    /**
       * 获取计划数据
       * @param options {?Object}
       */
    async getPlanData(options = {}) {
      // const [year, month] = this.date.split('-');
      this.tableLoading = true;
      const { success, data } = await this.$Model.getPlanNumber({
        year: '',
        month: '',
        project_id: this.projectId,
        ...options
      });
      this.tableLoading = false;
      if (success && Array.isArray(data.data)) {
        this.tableData = data.data.map(item => ({
          ...item,
          date: item.year + '-' + item.month
        }));
      }
    },
    // 获取历史记录
    getHistory() {},
    // 重置计划分页参数
    clearPlan() {
      this.pageSize = 10;
      this.pageNo = 1;
    },
    // 重置历史分页参数
    clearHistory() {
      this.historyPageSize = 10;
      this.historyPageNo = 1;
    },
    /**
       * pageSize 改变时会触发
       * @param pageSize 每页条数
       */
    handleSizeChange(pageSize) {
      this.pageNo = 1;
      this.pageSize = pageSize;
      this.getPlanData();
    },
    /**
       * currentPage 改变时会触发
       * @param pageNo 当前页
       */
    handleCurrentChange(pageNo) {
      this.pageNo = pageNo;
      this.getPlanData();
    },
    /**
       * 历史记录pageSize 改变时会触发
       * @param pageSize 每页条数
       */
    handleHistorySizeChange(pageSize) {
      this.historyPageNo = '1';
      this.historyPageSize = pageSize;
      this.getHistory();
    },
    /**
       * 历史记录currentPage 改变时会触发
       * @param pageNo 当前页
       */
    handleHistoryCurrentChange(pageNo) {
      this.historyPageNo = pageNo;
      this.getHistory();
    },
    // 新增计划
    handleAdd() {
      this.type = 'add';
      this.addVisible = true;
    },
    /**
       * 编辑计划
       * @param row {Object}
       */
    handleEdit({ plan_number, date }) {
      this.type = 'edit';
      this.addVisible = true;
      this.form = {
        plan_number,
        date
      };
    },
    /**
       * 删除计划
       * @param row {Object}
       */
    handleDelete(row) {
      this.$confirm('此操作将删除该计划, 是否继续?', '提示', {
        type: 'warning'
      }).then(async () => {
        const { year, month } = row;
        const { success } = await this.$Model.deletePlanNumber({
          year,
          month,
          project_id: this.projectId,
        });
        if (success) {
          this.$message.success('删除计划成功');
          this.clearPlan();
          this.getPlanData();
        }
      });
    },
    // 新建/编辑计划保存
    handleSubmit() {
      this.$refs.form.validate(async valid => {
        if (valid) {
          this.btnLoading = true;
          const time = this.$moment(this.form.date).format('YYYY-MM');
          const [year, month] = time.split('-');
          const params = {
            year,
            month,
            project_id: this.projectId,
            plan_number: this.form.plan_number
          };
          const { success } = this.type === 'add'
            ? await this.$Model.insertPlanNumber(params)
            : await this.$Model.updatePlanNumber(params);
          this.btnLoading = false;
          if (success) {
            this.$message.success(`${this.type === 'add' ? '新增' : '编辑'}计划成功`);
            this.type === 'add' && this.clearPlan();
            this.$emit('edit', time);
            this.addVisible = false;
            this.getPlanData();
          }
        }
      });
    },
    // 关闭、取消
    handleCancel() {
      this.$emit('cancel', false);
    }
  }
};
</script>

<style scoped lang="scss">
  @import '../../../assets/styles/dialog';

  .progress-download-excel-model {
    .btns {
      width: 100%;
      height: 20px;
      display: flex;
      justify-content: flex-end;
      padding: 0 20px;
      align-items: center;
      color: #fff;
      margin-bottom: 10px;
      i {
        font-size: 18px;
        margin-left: 10px;
        cursor: pointer;
        &.iconxinjian {
          font-size: 19px;
        }
        &:hover {
          color: $mainColor;
        }
      }
    }
    .table-content {
      .btn {
        color: $mainColor;
        cursor: pointer;
        margin-right: 5px;
        transition: color .2s;
        &:hover {
          color: $lightBtnBg;
        }
      }
    }
  }

  .add-plan-model {
    .el-date-editor {
      width: 100%;
    }
  }

</style>
